package com.example.es.service;

import com.alibaba.fastjson.JSON;
import com.example.es.model.Conter;
import com.example.es.util.HtmlJsoup;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: 朱超
 * @createDate: 2021/9/16
 * @version: 1.0
 * @remark：备注
 */
@Service
public class ConterServiceImpl implements ConterService {
    @Autowired
    private HtmlJsoup htmlJsoup;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean conter(String name) throws IOException {
        //解析
        List<Conter> list = htmlJsoup.list(name);
        //将查询的数据放入 ES
        BulkRequest bulkRequest = new BulkRequest();
        //设置超时时间
        bulkRequest.timeout("2m");
        for (int i = 0; i < list.size(); i++) {
            //将商品添加到这个 库中
            bulkRequest.add(
                    new IndexRequest("role")
//                            .id(String.valueOf(i + 1))
                            .source(JSON.toJSONString(list.get(i)), XContentType.JSON));
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures(); //没有失败就返回成功
    }

    //获取数据 实现搜索功能
    @Override
    public List<Map<String, Object>> search(String name, int pageNum, int pageSize) throws IOException {
        //判断当前页面 不为空
        if (pageNum == 0) {
            pageNum = 1;
        }
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("role");
        //构建搜索的条件   都是通过 SearchSourceBuilder 构建的
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //分页
        sourceBuilder.from(pageNum);
        sourceBuilder.size(pageSize);
        //精准匹配
        TermQueryBuilder title = QueryBuilders.termQuery("title", name);
        sourceBuilder.query(title);
        //设置超时时间
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //高亮数据显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.requireFieldMatch(false);//是否显示多个字段高亮
        highlightBuilder.field("title");//高亮的字段
        highlightBuilder.preTags("<span style='color: red '>");//前缀标签
        highlightBuilder.postTags("</span>");//后缀标签
        sourceBuilder.highlighter(highlightBuilder);  //将结果放进 highlighter 中
        //执行搜索 将构建的结果 放入 source
        searchRequest.source(sourceBuilder);
        //执行求情
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        //获取数据 【所有的数据都封装在 Hits 中】
//        SearchHits hits = search.getHits();
        //解析结果
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            //解析高亮字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title1 = highlightFields.get("title");
            //转换成  MAP 集合
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();//原来的结果
            //将高亮字段替换原来没高亮的字段
            if (title1 != null) {
                Text[] fragments = title1.fragments();
                String nameTitle="";
                for (Text text : fragments) {
                    nameTitle+=text;// 赋值
                }
                sourceAsMap.put("title",nameTitle);//将旧的 title 替换成 新的 title
            }
            //将map数据装到list中返回
            list.add(sourceAsMap);
        }
        return list;
    }
}
